package com.example.base.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

@Slf4j
public class JacksonUtil {

    private static ObjectMapper mapper;

    public static void setMapper(ObjectMapper mapper){
        JacksonUtil.mapper = mapper;
    }

    public static ObjectMapper getMapper(){
        return JacksonUtil.mapper;
    }

    public static String toJSONString(Object object){
        try {
            return mapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            log.error("对象序列化失败", e);
            return null;
        }
    }

    public static JsonNode toObjectNode(Object object){
        try {
            String json = toJSONString(object);
            return mapper.readTree(json);
        } catch (JsonProcessingException e) {
            log.error("对象序列化失败", e);
            return null;
        }
    }

    /**
     * 只能简单的对象转换 若对象内部存在泛型需要单独处理
     * @param json
     * @param clz
     * @return
     * @param <T>
     */
    public static <T> T toJavaType(String json, Class<T> clz){
        if (StringUtils.isBlank(json)){
            return null;
        }
        try {
            return mapper.readValue(json, clz);
        } catch (Exception e) {
            log.error("对象序列化失败", e);
            return null;
        }
    }
}
